using System.IO;
using System.Text;
using System.Web;

namespace Mvc.XForms.Utilities {
	public class ResponseCapturer  {
		private CapturingResponseFilter captureFilter;
		private HttpResponseBase resp;
		private Stream originalFilter; 

		public ResponseCapturer(HttpResponseBase resp) {
			this.resp = resp;
		}

		public void InitCapturing() {
			originalFilter = resp.Filter;
			captureFilter = new CapturingResponseFilter(originalFilter);

			// Clear response buffer
			resp.Flush();

			// Assign filter to write response to memory
			resp.Filter = captureFilter;
		}

		public string ReadAndReset() {
			// Clear the buffer again
			resp.Flush();

			// Finally set the filter back to normal HTTP filter
			resp.Filter = originalFilter;

			var output = captureFilter.GetContents(resp.ContentEncoding);

			return output;
		}
	}
}